<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/7/17
 * Time: 10:51
 */
namespace app\home\controller;
//include '/data/wwwroot/health.xuanwumobile.com/vendor/autoload.php'; // 引入 composer 入口文件
use think\Db;
use think\Config;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use think\Controller;
class Car extends Common
{
    /**
      * 购物车首页
     */
    public function index()
    {
        $auth = $this->checkAll();
        $openid = $this->getOpenid();
        $user = Db::table('up_u_user')
            ->where('user_openid', $openid)
            ->find();
        if(!$user){
            return $this->fetch('login/login');
        }else{
            $user_id = $user['user_id'];
            $where = array();
            $where['car_userid'] = $user_id;
            $where['car_status'] = 1;
            //1、先分组商家，取得分组数据
            $data = Db::table('up_shopping_car')->alias('car')
                ->join('up_shops s','car.car_shopid=s.s_id','LEFT')
                ->where($where)
                ->where('s_status',1)//正常的商户
                ->order('car_time DESC')
                ->group('car_shopid')
//            ->field('')
                ->page(1,5)
                ->select();
            if($data){
                foreach ($data as $k=>$v){
                    $data[$k]['manjian'] = 1;//1是不满减
                    //-----------------
                    $today = date('Y-m-d');
                    $mjyh = Db::table('up_shop_active')
                        ->where('sa_shopid',$v['car_shopid'])
                        ->where('sa_start','<=',$today)
                        ->where('sa_end','>=',$today)
                        ->find();
                    if($mjyh){
                        $data[$k]['manjian'] = 2;//2是满减
                        $data[$k]['manjian_rule'] = $mjyh['sa_rule'];//规则
                        $data[$k]['manjian_rule_str'] = $mjyh['sa_rule_con'];//规则字符串
                    }
                    //-----------------
                    $where['car_shopid'] = $v['car_shopid'];
                    //商品必须存在
                    $where['g_status'] = 1;
                    $where['g_id'] = array('>',0);
                    //TODO
                    $goods = Db::table('up_shopping_car')->alias('car')
                        ->join('up_goods g','car.car_goodid=g.g_id','LEFT')
                        ->where($where)
                        ->order('car_time DESC')
                        ->select();
                    if(!$goods){
                        unset($data[$k]);
                    }else{
                        $data[$k]['goods'] = $goods;
                    }
                }
            }
            $this->assign('data',$data);
            return $this->fetch('car/index');
        }
    }
    /**
     * 删除一个购物车
     */
    public function deleteMyCar(){
        extract(input());
        $auth = $this->checkAll();
        $car = Db::table('up_shopping_car')->where('car_id',$car_id)->find();
        $res = Db::table('up_shopping_car')
            ->where('car_userid',$car['car_userid'])
            ->where('car_shopid',$car['car_shopid'])
            ->delete();
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'删除失败']);
        }

    }
    /**
     * 确认订单页1——确认
     * 购物车的id集合:carids
     * 收货地址id:add_id
     * 备注:remark（怎么传值）
     * 那方支付：type（1是支付宝  2是微信）
     */
    public function sureOrder(){
        extract(input());
        $auth = $this->checkAll();
        $openid = $this->getOpenid();
        $user = Db::table('up_u_user')
            ->where('user_openid', $openid)
            ->find();
        if(!$user){
            return $this->fetch('login/login');
        }
        $user_id = $user['user_id'];
        //---------------结合下这几个判断-------------------------
        $today = date('Y-m-d');
        $where = array();
        $where['car_userid'] = $user_id;
        $where['car_status'] = 1;
        $where['car_shopid'] = $shopid;
        //商品必须存在
        $where['g_status'] = 1;
        $where['g_id'] = array('>',0);
        //1、先分组商家，取得分组数据
        $shop = Db::table('up_shops')
            ->where('s_id',$shopid)
            ->find();
        $goods = Db::table('up_shopping_car')->alias('car')
            ->join('up_goods g','car.car_goodid=g.g_id','LEFT')
            ->where($where)
            ->select();
        $data = array();
        $packfei = 0;//1、、、包装费
        $allmoney = 0;//2、、、所有商品金额
        $manjian = 0;//3-1、、、满减的判断依据（非秒杀商品的金额）
        foreach ($goods as $k2 => $v2) {
            $packfei += $v2['g_pack'] * $v2['car_number'];//包装费
            if ($v2['g_prcie_kill'] != 0 && $v2['g_kill_start'] <= $today && $v2['g_kill_end'] >= $today) {
                $allmoney += $v2['g_prcie_kill'] * $v2['car_number'];//秒杀价
            } else {
                $allmoney += $v2['g_price_now'] * $v2['car_number'];//非秒杀的价格
                $manjian += $v2['g_price_now'] * $v2['car_number'];//非秒杀时满减的判断依据
            }
        }
        $post = 0;//4、、、邮费
        if ($allmoney < $shop['s_mianyou']) {
            $post = $shop['s_post'];//配送费就是邮费
        }
        //满减信息计算
        $manjianMoney = 0;//3-2、、、满减了多少
        $mjyh = Db::table('up_shop_active')
            ->where('sa_shopid', $shop['s_id'])
            ->where('sa_start', '<=', $today)
            ->where('sa_end', '>=', $today)
            ->find();
        if ($mjyh) {
            $rule = trim($mjyh['sa_rule'], ',');//规则
            $rule_arr = explode(',', $rule);
            foreach ($rule_arr as $vv) {
                $vv_arr = explode('-', $vv);
                if ($manjian >= $vv_arr[0]) {
                    $manjianMoney = $vv_arr[1];
                }
            }

        }
        $pay = $allmoney + $packfei + $post - $manjianMoney;
        $data['allmoney'] = $allmoney;//商品总额
        $data['packfei'] = $packfei;//包装费
        $data['post'] = $post;//配送费
        $data['manjianMoney'] = $manjianMoney;//优惠金额
        $data['pay'] = $pay;//用户实际支付金额
        $this->assign('data',$data);
        $this->assign('shop',$shop);
        $this->assign('goods',$goods);
        $this->assign('length',count($goods));
        //有关地址
        $address = array();
        if(isset($aid)){
            $add = Db::table('up_user_address')
                ->where('add_id', $aid)
                ->find();
            $address['aid'] = $aid;
            $address['address'] = $add['add_address'];
            $address['username'] = $add['add_username'];
            $address['phone'] = $add['add_phone'];
        }else{
            $add2 = $this->getNearAddressOne($user_id,$shop['s_lat'],$shop['s_lon']);
            if($add2){
                $address['aid'] = $add2['add_id'];
                $address['address'] = $add2['add_address'];
                $address['phone'] = $add2['add_phone'];
                $address['username'] = $add2['add_username'];
            }else{
                $address['aid'] = 0;
                $address['address'] = '';
                $address['phone'] = '';
                $address['username'] = '';
            }
        }
        $this->assign('address',$address);
        $this->assign('user_id',$user_id);
        return $this->fetch('car/sure_order');
    }
    /**
     * 获取附近的符合的收货地址的其中一个
     * lat  lon
     * @return string
     */
    public function getNearAddressOne($user_id,$lat,$lon)
    {
        $where = array();
        $where['add_userid'] = $user_id;
        $mile = Db::table('up_set_juli')->where('juli_id',2)->value('juli_value');
        $miles = $mile*1000;
        $field = 'add_id,add_lat,add_lon,add_phone,add_address,add_username,add_sex,add_type';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - add_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(add_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - add_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $data = Db::table('up_user_address')
            ->field($field)
            ->where($where)
            ->having("distance <= $miles")
            ->order('add_type DESC,distance ASC')
            ->find();
        return $data;
    }
    /**
     * 获取附近的符合的收货地址
     * lat  lon
     * @return string
     */
    public function getNearAddress()
    {
        extract(input());
        $this->checkAll();
        $openid = $this->getOpenid();
        $user_id = Db::table('up_u_user')
            ->where('user_openid', $openid)
            ->value('user_id');
        $where = array();
        $where['add_userid'] = $user_id;
        $mile = Db::table('up_set_juli')->where('juli_id',2)->value('juli_value');
        $miles = $mile*1000;
        $field = 'add_id,add_lat,add_lon,add_phone,add_address,add_username,add_sex,add_type';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - add_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(add_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - add_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $data = Db::table('up_user_address')
            ->field($field)
            ->where($where)
            ->having("distance <= $miles")
            ->order('add_type DESC,distance ASC')
//            ->page($page,15)
            ->select();
        $this->assign('address',$data);
        $this->assign('shopid',$shopid);
        $this->assign('lat',$lat);
        $this->assign('lon',$lon);
        return $this->fetch('car/address');
    }
    /**
     * @return \think\response\Json
     */
    public function addAdd(){
        extract(input());
        $data = array();
        $data['name'] = '';
        $data['phone'] = '';
        $data['sex'] = '';
        $data['lat'] = '';
        $data['lon'] = '';
        $data['address'] = '';
        $data['door'] = '';
        if(isset($name)){$data['name'] = $name;}
        if(isset($phone)){$data['phone'] = $phone;}
        if(isset($sex)){$data['sex'] = $sex;}
        if(isset($lat)){$data['lat'] = $lat;}
        if(isset($lon)){$data['lon'] = $lon;}
        if(isset($address)){$data['address'] = $address;}
        if(isset($door)){$data['door'] = $door;}
        $this->assign('data',$data);
        $this->assign('type',2);
        $this->assign('shopid',$shopid);
        $this->assign('lat',$lat2);
        $this->assign('lon',$lon2);
        return $this->fetch('car/add_address');
    }
    public function addressLocation(){
        extract(input());
        $data = array();
        $data['name'] = '';
        $data['phone'] = '';
        $data['sex'] = '';
        $data['lat'] = '';
        $data['lon'] = '';
        $data['address'] = '';
        if(isset($name)){$data['name'] = $name;}
        if(isset($phone)){$data['phone'] = $phone;}
        if(isset($sex)){$data['sex'] = $sex;}
        if(isset($lat)){$data['lat'] = $lat;}
        if(isset($lon)){$data['lon'] = $lon;}
        if(isset($address)){$data['address'] = $address;}
        if(isset($door)){$data['door'] = $door;}
        $this->assign('type',1);
        $this->assign('data',$data);
        $this->assign('lat',$lat2);
        $this->assign('lon',$lon2);
        $this->assign('shopid',$shopid);
        return $this->fetch('car/location_address');
    }
    /**
     * 确认订单页2——支付
     * 收货地址id:add_id
     * 备注:remark（怎么传值）
     * 那方支付：type（1是支付宝  2是微信）
     */
    public function makeOrder(){
        extract(input());
        $auth = $this->checkAll();
        $number = date('YmdHis') . rand(1000000,9999999);
        //1、先分组商家，取得分组数据
        $shop = Db::table('up_shops')
            ->where('s_id',$shopid)
            ->find();
        if($shop['s_status'] != 1){
            return 4;
        }
        $today = date('Y-m-d');
        $openid = $this->getOpenid();
        Db::startTrans();
        try{
            $orderId = Db::table('up_order')->insertGetId(['order_userid' => $user_id]);
            //---------------结合下这几个判断-------------------------
            $where = array();
            $where['car_userid'] = $user_id;
            $where['car_status'] = 1;
            $where['car_shopid'] = $shopid;
            //商品必须存在
            $where['g_status'] = 1;
            $where['g_id'] = array('>', 0);
            //---------------------end------------------
            $goods = Db::table('up_shopping_car')->alias('car')
                ->join('up_goods g', 'car.car_goodid=g.g_id', 'LEFT')
                ->where($where)
                ->select();
            $allmoney = 0;
            $manjian = 0;
            $packfei = 0;
            $allcount = 0;
            $order = array();
            foreach ($goods as $k2 => $v2) {
                //1、首先是不是可买份数变了
                if ($v2['g_canbuy'] != 0 && $v2['g_canbuy'] > 0) {
                    if ($v2['car_number'] > $v2['g_canbuy']) {
                        return 100;
                    }
                }
                //3、入info
                $oi = array();
                $oi['oi_order_id'] = $orderId;
                //2、价格(包装费，总价，满减价参考)
                $packfei += $v2['g_pack'] * $v2['car_number'];//包装费
                $allcount += $v2['car_number'];//所买商品的数量

                if ($v2['g_prcie_kill'] != 0 && $v2['g_kill_start'] <= $today && $v2['g_kill_end'] >= $today) {
                    $allmoney += $v2['g_prcie_kill'] * $v2['car_number'];//秒杀价
                    $oi['oi_price_kill'] = $v2['g_prcie_kill'];//详情的秒杀判断
                } else {
                    $allmoney += $v2['g_price_now'] * $v2['car_number'];//非秒杀的价格
                    $manjian += $v2['g_price_now'] * $v2['car_number'];//非秒杀时满减的判断依据
                }
                //------------减库存
                if($v2['g_stock'] != -1){
                    if($v2['g_stock'] >= $v2['car_number']){
                        Db::table('up_goods')
                            ->where('g_id',$v2['g_id'])
                            ->setDec('g_stock',$v2['car_number']);
                    }else{
                        return 5;
                    }

                }
                //------------------
                //3、入info
                $oi['oi_good_id'] = $v2['g_id'];
                $oi['oi_shop_id'] = $v2['g_shop'];
                $oi['oi_price_before'] = $v2['g_price_before'];
                $oi['oi_price_now'] = $v2['g_price_now'];
                $oi['oi_num'] = $v2['car_number'];
                $oi['oi_good_name'] = $v2['g_name'];
                $oi['oi_good_thumb'] = $v2['g_thumb'];
                $oi['oi_good_pack'] = $v2['g_pack'];
                Db::table('up_order_info')->insertGetId($oi);
                Db::table('up_shopping_car')->where('car_id',$v2['car_id'])->delete();
            }
            $order['order_number'] = $number;
            $order['order_userid'] = $user_id;
            $order['order_num'] = $allcount;
            $order['order_shopid'] = $shopid;
            //收件人信息
            $address = Db::table('up_user_address')
                ->where('add_id', $add_id)
                ->find();
            $order['order_address_sex'] = $address['add_sex'];
            $order['order_address'] = $address['add_address'];
            $order['order_address_phone'] = $address['add_phone'];
            $order['order_address_name'] = $address['add_username'];
            //============
            $post = 0;
            $order['order_money_all'] = $allmoney;
            if ($allmoney < $shop['s_mianyou']) {
                $order['order_money_send'] = $shop['s_post'];//配送费就是邮费
                $post = $shop['s_post'];//配送费就是邮费
            }
            $order['order_money_pack'] = $packfei;
            //满减信息计算
            $order['order_money_man'] = 0;
            $mjyh = Db::table('up_shop_active')
                ->where('sa_shopid', $shop['s_id'])
                ->where('sa_start', '<=', $today)
                ->where('sa_end', '>=', $today)
                ->find();
            if ($mjyh) {
                $rule = trim($mjyh['sa_rule'], ',');//规则
                $rule_arr = explode(',', $rule);
                foreach ($rule_arr as $vv) {
                    $vv_arr = explode('-', $vv);
                    if ($manjian >= $vv_arr[0]) {
                        $order['order_money_man'] = $vv_arr[1];
                    }
                }

            }
            //满减信息计算end
            $order['order_remark'] = $remark;
            $order['order_type'] = 2;
            $order['order_where'] = 2;
            $order['order_time'] = date('Y-m-d H:i:s');
            $order['order_user_pay'] = $allmoney + $packfei + $post - $order['order_money_man'];
            Db::table('up_order')->where('order_id', $orderId)->update($order);
            $pay = $order['order_user_pay'];
            Db::commit();
            //----------------------------------------------
            //===================================================================================
            $options = Config::get('wechat');
            $options['payment']['notify_url'] ='http://mww5.xuanwumobile.com/home/Car/huidiao';
            $app = new Application($options);
            $payment = $app->payment;
            //---------------------------2
            $attributes = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                'body'             => "红集网",
                'detail'           => "商品购买",
                'out_trade_no'     => "$number",
                'total_fee'        => 1,//*100, // 单位：分
                'notify_url'       => 'http://mww5.xuanwumobile.com/home/Car/huidiao', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'openid'           => "$openid", // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                // ...
            ];
            $order = new Order($attributes);
            //--------------------------------3
            $result = $payment->prepare($order);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $json = $payment->configForPayment($prepayId);
                return view('car/pay_done',['json'=>$json]);
            }else{
                return  1;
            }
        }catch (\Exception $e) {
            Db::rollback();
            return 2;
        }
    }
    public function huidiao()
    {
        $options = Config::get('wechat');
        $options['payment']['notify_url'] ='http://mww5.xuanwumobile.com/home/Car/huidiao';
        $app = new Application($options);
        $response = $app->payment->handleNotify(function($notify, $successful){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
//            $order = 查询订单($notify->out_trade_no);
            // 用户是否支付成功
            if ($successful) {
                Db::startTrans();
                try{
                    $number =$notify->out_trade_no;
                    $transaction_id = $notify['transaction_id'];
                    $paytime = $this->getDateBytimeDate("{$notify['time_end']}");
                    $order = Db::table('up_order')->where('order_number', $number)->find();
                    //1、支付成功改状态
                    $update = array();
                    $update['order_status'] = 2;
                    $update['order_back_transaction_id'] = $transaction_id;
                    $update['order_paytime'] = $paytime;
                    $update['order_paydate'] = substr($paytime,0,10);
                    Db::table('up_order')
                        ->where('order_number', $number)
                        ->update($update);
                    //2、商户改余额
                    $money = Db::table('up_shops')->where('s_id', $order['order_shopid'])->value('s_money');
                    $money += $order['order_user_pay'];
                    Db::table('up_shops')
                        ->where('s_id', $order['order_shopid'])
                        ->update(['s_money'=>$money]);
                    Db::commit();
                    return true;
                }catch (\Exception $e) {
                    Db::rollback();
                    return 'database error';
                }
            } else { // 用户支付失败
                return 'pay false';
            }
        });
        $response->send();
    }
    /**
     * 商户处理用户的退款：从公众号这买的
     * @return array
     */
    public function WeChatTuikuan($payinfo)
    {
        $options = Config::get('wechat');
        $app = new Application($options);
        $payment = $app->payment;
        $tuinum = date('YmdHis').rand(1000000,9999999);
        $result = $payment->refund($payinfo['number'], $tuinum, 1);//$payinfo['money']*100); // 总金额 100 退款 100，操作员：商户号
        $res = $result->toArray();
        if($res['result_code'] == 'SUCCESS'){
            $err['status'] = 200;
            $err['msg'] = '退款成功';
            return $err;
        }else{
            $err = array();
            $err['status'] = 0;
            $err['msg'] = $res['err_code_des'];
            return $err;
        }

    }
}